package com.csw.shuanfa.CodeImprove.CompleteFutureLinkedBlockingQueue;

import com.csw.shuanfa.utils.ThreadPoolUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

public class CallableTest {
    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        int num = 10;
        ExecutorService executorServiceCPU = ThreadPoolUtil.getExecutorServiceCPU();

        try {
            AtomicInteger a = new AtomicInteger();
            long t1 = System.currentTimeMillis();
            Callable<Object> call = getObjectCallable(a, executorServiceCPU);

            List<Future<Object>> mathContexts = new ArrayList<>();
            for (int i = 0; i < num; i++) {
                //调用每个步骤
                Future<Object> future = executorServiceCPU.submit(call);
                //封装future
                mathContexts.add(future);
            }
            //后续遍历获取
            //异步处理，每个步骤执行完获取
            for (int i = 0; i < mathContexts.size(); i++) {
                Future<Object> future = mathContexts.get(i);
                //设置超时获取时间
                Object obj = future.get(3000 * 1, TimeUnit.MILLISECONDS);
            }
            long t2 = System.currentTimeMillis();

            //t2 - t1);
            //a.get());
        } catch (TimeoutException ex) {
            //处理超时啦....");
            ex.printStackTrace();
        } catch (Exception e) {
            //处理失败.");
            e.printStackTrace();
        }

    }

    private static Callable<Object> getObjectCallable(AtomicInteger a, ExecutorService singleThreadPool) {
        Callable<Object> call = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                //开始执行耗时操作
                Thread.sleep(2000);//每个任务的处理时间
                a.getAndIncrement();
                //Thread.currentThread().getName());
                return null;
            }
        };
        return call;
    }

}
